<?php
/**
 * @filesource modules/event/controllers/IndexController.php
 * @author Dao Quang Duc
 * @abstract : List of actions in order
 *   - new
 *   - view
 *   - edit
 *   - delete
 *   - search
 */ 
class Event_MasterController extends Clu_Controller_Action_Master
{
	public $m,$c;//, $mPlace, $mArticle;
	
	public function init()
	{
		//require_once (APP_PATH.'/modules/place/Model/City.php');
		//require_once (APP_PATH.'/modules/place/Model/District.php');
		//require_once (APP_PATH.'/modules/place/Model/Village.php');
		//require_once (APP_PATH.'/modules/place/Model/Vicinity.php');
		//require_once (APP_PATH.'/modules/place/Model/Place.php');
		//require_once (APP_PATH.'/modules/category/Model/Category.php');
		//require_once (APP_PATH.'/modules/article/Model/Article.php');
		//require_once (APP_PATH.'/modules/user/Model/User.php');
		//require_once (APP_PATH.'/modules/comment/Model/Comment.php');
		$this->mArticle = new article_Model_Service();
		$this->m = new event_Model_Service();
		$this->mCategory = new category_Model_Category();
		$this->mCategory->setTables('event');
		$this->mPlace = new place_Model_Place();
		$this->mCity = new place_Model_City();
		$this->mDistrict = new place_Model_District();
		
		parent::init();
		
	}
	
	public function newAction() 
	{
	   //check user permissions here
        $sess = new Zend_Session_Namespace(CLU_NS);
        if (strpos ($sess->userPermissions, 'create event') === false)
        {
            $this->renderError(null,t(68));
            return;
        }
		$placeId = $this->_request->getParam('place_id');
		$this->viewParams['form'] = new event_Form_Event();
        $actionUrl = $this->view->hvnUrl(array('module' => 'event', 'action'=>'new'), 'nocontroller');
        $this->viewParams['form']->cluBuild(array('action' => 'new', 'action_url' => $actionUrl, 
                                                          'userPermissions' => $sess->userPermissions, 
                                                          'language' => $sess->viewLang ));
        
        if ($placeId)
		{   
	        $this->viewParams['place_id'] = $placeId;
	        $this->viewParams['belong_to_names_submit'] = $this->_request->getParam('belong_to_names_submit');
	        $placeData = $this->mPlace->findByPrimary($placeId);
	        $cityName = unserialize($placeData['metadata']);
	        $this->viewParams['cityName'] = $cityName['city_name'];
	        $a = array();
	        $keys = array('city_id', 'district_id', 'village_id', 'address5', 'address6', 'address7', 'address8', 'address9');
	        $a = clu_array_merge($keys, $placeData);
	        $this->viewParams['form']->populate($a);
	        $this->viewParams['form']->populateEventForm($a);
		}
        $this->viewParams['mode'] = "new";
        
    	$data = $this->_request->getParams();
        if ($this->_request->isPost() && $this->viewParams['form']->isValid($_POST)) 
        {
        	$db = $this->db;
	        $db->beginTransaction(); //TODO: to be moved to Model in v2
            try 
            {
            	$data['article_title'] 		= $data['title'];
            	$data['article_body']  		= $data['description'];
            	$data['article_language'] 	= $data['eventLanguage'];
            	$data['article_module'] 	= "event";
            	$data['article_keywords'] 	= $data['keywords'];
            	$data['article_status'] 	= isset($data['status']) ? $data['status'] : 
            		Zend_Registry::get('configuration')->general->defaultNodeStatus;
            	//die_a($placeId);
                if (!$this->mArticle->insertRaw($data,false))
                if (!$this->mArticle->insertRaw($data,array('do_validate' => false)))
                {
                	$this->view->errorMessage = t(503);
                }
                $article_id = $db->lastInsertId();
            	$data['article_id'] = $article_id;
    			if($article_id != 0)
                {
		            try
			    	{
			    	   	$eventId = $this->m->insertRaw($data,array('do_validate' => false));
			            if(isset($data['belong_to_ids']))
			            	$this->mPlace->relatedEvent($data['belong_to_ids'], $eventId, null);
			    	}
			    	catch (Exception $e) 
			    	{
			    		//die($e->getMessage());
			    	    $this->viewParams['errorMessage'] = t(214);
			    		$this->mArticle->deleteByPrimary(array($article_id), false);
			    	}
                }
                $db->commit();
            }
            catch (Exception $e)
            {
                $db->rollBack();
                $this->viewParams['errorMessage'] .= "<br/>" . t(69);
            }
	    	
            if (empty($this->viewParams['errorMessage']))
            {
            	$url = $this->view->hvnUrl(array('module'=>'event', 'action'=>'gallery'));
    			$this->_helper->redirector->gotoUrl($url . '?id='.$eventId); //TODO
//				$this->_forward("success", 'index' , 'event', array('lastInsertId' => $article_id, 'lang' => 'en' ) );
    	    	return;
            }
            
        }
        else if ($this->_request->isPost() )
        {
        	$this->viewParams['errorMessage'] = t(1);
        }
        //Populate form & rtype options 
        $categoryId = $this->_request->getParam("category");
        $this->viewParams['form']->populateEventForm( $data);
	}
	
	public function viewAction() 
	{
		$id = $this->_request->getParam("id");
    	$e = $this->m->findByPrimary($id);
	 	if(!$event = $this->m->getData($id,array('get_article' => true)))
        {
            $this->renderError(null,t(209));
            return;
        }
	 	$sess = new Zend_Session_Namespace(CLU_NS);
        if ($event['article']['article_language'] != $sess->viewLang)
            $this->viewParams['errorMessage'] = sprintf(t(519),  $sess->viewLang );
            							   
        if (strpos ($sess->userPermissions, 'read event') === false)
        {
            $this->renderError(null,t(70));
            return;
        }
		$this->viewParams['lang'] = $sess->viewLang;
        $this->viewParams['oriLang'] = $event['article']['article_language'];
        $this->viewParams['articleBody'] = $event['article']['article_body'];
        $this->viewParams['articleTitle'] = $event['article']['article_title'];
        $this->viewParams['article_post_time'] = $event['article']['article_post_time'];
        $this->viewParams['event'] = $this->m->transformToFormArray('edit',$e);
//        $dataEvent = $this->m->search(array('status' => 'published'));
//        $this->viewParams['old_news'] = $this->db->fetchAll($dataEvent);
        $this->m->updateDbAfterView($id);
        //$this->renderToHolder('index/view.phtml', false, null, 4, 1); 
        $this->paramsForWidgets['gallery_id'] = $event['gallery'];
		$this->paramsForWidgets['content_type'] = "event";
		$this->paramsForWidgets["type"] = "event";
		$this->paramsForWidgets["category"] = $event['category'];
		$this->paramsForWidgets['content_id'] = $id;
        $this->paramsForWidgets["id"] = $id;
        $this->paramsForWidgets['content_poster_id'] = $event['poster_id'];
		
	}
	
	public function editAction()
	{
        //check user permissions here
        $sess = new Zend_Session_Namespace(CLU_NS);
        if (strpos ($sess->userPermissions, 'create event') === false)
        {
            $this->renderError(null,t(68));
            return;
        }
        
    	$id = $this->_request->getParam("id");
    	if (!$e = $this->m->findByPrimary($id))
        {              
            $this->renderError(null,t(209));
            return;
        }
        
		//check for permission here
		//check rights
		if (!isset($sess->userId))
		{
		 	$this->renderError(null,t(726));
        	return;	
		}
		
		if (($sess->userId != $e->poster_id && strpos($sess->userPermissions, 'update event') === false) ||
				($sess->userId == $e->poster_id && strpos ($sess->userPermissions, 'update own event') === false))
		{
		 	$this->renderError(null,t(210));
        	return;	
		}
		
		
        //everything's fine. Continue editing
        $this->viewParams['form'] = new event_Form_Event();
//     	$this->viewParams['form']->cluBuild(array ('action' => 'edit','view' => $this->view, 
//							   'userPermissions' => $sess->userPermissions, 'place_id' => $e['place_id']));
     	
     	$actionUrl = $this->view->hvnUrl(array('module' => 'event', 'action'=>'edit'), 'nocontroller');
        $this->viewParams['form']->cluBuild(array('action' => 'edit', 'action_url' => $actionUrl, 
                                                          'userPermissions' => $sess->userPermissions, 
                                                          'language' => $sess->viewLang ));
        
        /*
		if(isset($e['place_id']))
		{
			$dataPlace = unserialize($e['metadata']);
			$this->view->placeData = $dataPlace;
		}
		*/
        if ( $this->viewParams['form']->isValid($_POST))
        {	
			$data = $this->_request->getParams();
        	$articleData = array();
            $articleData['article_title'] = $data['title'];
            $articleData['article_body'] = $data['description'];
            $article_id = $data['article_id'];
            if (!($this->mArticle->saveRaw(null, $articleData, $article_id,array('do_validate' => false))))
            {
            	$this->viewParams['errorMessage'] = t(503);
            }
            
            if($e->place_id != $data['belong_to_ids'])
        	{
        		$this->mPlace->relatedEvent($data['belong_to_ids'], $id, $e->place_id);
        	}
        	
            if ($this->m->saveRaw($e, $data, $id, array('do_validate' => false)))
            {
    		 	$this->viewParams['successMessage'] = t(211);
    		 	$this->viewParams['form']->populateEventForm ($e);
            }
            else
                $this->viewParams['errorMessage'] = t(212);
        }
        else
        { 
        	//$this->viewParams['errorMessage'] = t(71);
            //Populate form 
	         $this->viewParams['form']->populateEventForm ($e);
        }
		
		$fData = unserialize($e->metadata);
        if(isset($e->place_id) && isset($fData['place_name']))
        {
	        $this->viewParams['place_id'] = $e->place_id;
        	$this->viewParams['belong_to_names_submit'] = $fData['place_name'];
        	$this->viewParams['cityName'] = $fData['city_name'];
        }
        
		$this->viewParams['article_id'] = $e['article_id'];
        $this->viewParams['id'] = $id;
        $this->viewParams['mode'] = 'edit';
        $this->viewParams['lang'] = Zend_Registry::get('viewLang');
        
	}

	public function searchAction()
    {
    	//unset($_SESSION['paginator']);
    	$requestData = $this->_request->getParams();
    	$this->paramsForWidgets['content_type'] = "event";
    	$data = $this->prepareDataSearch($requestData);
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	
		if (strpos($sess->userPermissions, "administer event"))
			$cluSearchMode = "fullAdminSearch";
	    else
			$cluSearchMode = "fullSearch";
		
      	$this->viewParams['form'] = new event_Form_EventSearch();
      	$actionUrl = $this->view->hvnUrl(array('module' => 'event', 'action'=>'search'), 'nocontroller');
        $this->viewParams['form']->cluBuild(array('action' => 'search', 'action_url' => $actionUrl, 
        												  'cluSearchMode' => $cluSearchMode,
                                                          'userPermissions' => $sess->userPermissions, 
                                                          'language' => $sess->viewLang ));
        
		if (isset($data['cluSearch']) || $this->_request->isPost())
		{
			if(isset($data['quick_time_range_mode']))
    			{
    				switch($data['quick_time_range_mode'])
    				{
    					case 1:
    					{
    						$data['startDate'] = date("d/m/Y",time());
    						$data['finishDate'] = date("d/m/Y",time() + 604800); // 604800s = 7days
    						break;
    					}
    					
    					case 2:
    					{
    						$data['startDate'] = date("d/m/Y",time());
    						$data[ 'finishDate'] = date("d/m/Y",time() + 2592000); // 2592000s = 30days
    						break;
    					}
    					
    					case 3:
    					{
    						$data['startDate'] = date("d/m/Y",time());
    						$data[ 'finishDate'] = date("d/m/Y",time() + 7776000); // 7776000s = 90days
    						break;
    					}
    				}
    				$data['quick_time_range_mode'] = NULL;
    			}
			
	    	if($paginator = $this->m->search($data))
    		{
    			$paginator= $this->generatePaginator($paginator, $data['page'], $data['events_per_page'], 7, 'Jumping');
                $this->viewParams['form']->populateDataSearch($data);  //$data['events_per_page']
//	            if(isset($data['district_id']) && is_array($data['district_id']))
//	    			$data['district_id'] = implode(',', $data['district_id']);
		        $searchUrl = encode_search_url($data, null, "event");
				//$this->viewParams['searchUrl'] = $searchUrl;
				$this->viewParams['searchUrl'] = 
					"http://" . SITE_URL . $this->view->hvnUrl(array('action' => 'search', 'module' => 'event'),'nocontroller') . "?$searchUrl";
        	}
		}
		
		$this->viewParams['listCategory'] = $this->mCategory->getRootType('Root_Event');
		if(isset($data['category']))
		{
			$this->viewParams['category'] = $data['category'];
			$this->viewParams['categoryName'] = $this->mCategory->getCategoryName($data['category']);
			//$this->viewParams['listType'] = $this->mCategory->getTree($data['rtype'], 1, 1);
		}

		$this->viewParams['listCity'] = $this->mCity->findForSelect();
		if(!empty($data['city_id']))
		{
			$this->viewParams['cityId'] = $data['city_id'];
			$this->paramsForWidgets['city_id'] = $this->viewParams['cityId'];
			$cityName = $this->mCity->getCityName($data['city_id']);
			$this->viewParams['cityName'] = $cityName['city_name'];
			$this->viewParams['listDistrict'] = $this->mDistrict->getDistricts($data['city_id']);
			
			if(!empty($data['district_id']))
			{
				$this->viewParams['districtId'] = $data['district_id'];
				$this->viewParams['dist_Id'] = implode(',', $data['district_id']);
				$this->paramsForWidgets['district_id'] = $data['district_id'];
				foreach($data['district_id'] as $dis)
				{
					$districtName[$dis] = $this->mDistrict->getDistrictName($dis);
				}
				foreach($districtName as $disName)
					$district_Name[] = $disName['district_name'];
				$this->viewParams['districtName'] = implode(',', $district_Name);
			}
		}
		
        if(isset($paginator))
       	{                
            $this->viewParams['paginator'] = $paginator;
        	foreach($paginator->getCurrentItems() as $temp)
        	{
            	$tmp = $this->m->transformToFormArray('edit',$temp);
        		$List[] = $tmp;
        	}
        	
            if (isset($List))
            {
    			$this->viewParams['eventList'] = $List;//list of found events
				$articleList = array();
				$mArticle = new article_Model_Service();
				foreach ($this->viewParams['eventList'] as $e)
				{
					$articleList[$e['id']] = $mArticle->getArticleData($e['article_id']);
				}
				$this->viewParams['aList'] = $articleList;
	
				$t = $this->_request->getParam('page');
				$pageNum  = !empty($t) ? $t : 1; 
				$perPage = isset($data['events_per_page']) ? $data['events_per_page']:  $data['search_params']['events_per_page'];
				$this->viewParams['startIndex'] = $perPage * ($pageNum - 1);
				$this->viewParams['numberOfItems'] = $paginator->getTotalItemCount();
				$this->viewParams['perPage'] = $perPage;
				$this->viewParams['pageNum'] = $pageNum;
				$this->viewParams['numberOfPages'] = ceil($this->viewParams['numberOfItems']/$this->viewParams['perPage']);  
            }
            if (strpos($sess->userPermissions, "administer event"))
            	$this->presenceIdentifier = 2;
//	            $this->renderToHolder('index/list_admin.phtml',false, null, 4,2);
//	        else
//	        	$this->renderToHolder('index/list.phtml',false, null, 4,2);
       	}
       	//$this->view->lang = Zend_Registry::get('viewLang');
       	//$this->renderToHolder('index/'.$cluSearchMode . '.phtml',false, null, 4,1); //search box
		
    }

	public function successAction()
    {
         $this->viewParams['commentId'] =  $this->_request->getParam("lastInsertId");
         //$this->renderToHolder( 'common/success.phtml');  
    }
    
    public function galleryAction()
    {
        $placeId = $this->_request->getParam('id');
        $sess = new Zend_Session_Namespace(CLU_NS);
	    if (!$p = $this->m->findByPrimary($placeId))
        {
        	$this->renderError(null,t(725));
        	return;	
        }
        //check user rights
       	if (strpos ($sess->userPermissions, 'update event') === false && 
       		($sess->userId != $p->poster_id)
       		)
	    {
	    	$this->renderError(null,t(68));
            return;
	    }
        
		//pas the gallery id to the gallery/widget/upload-photos        
        if ($p->gallery)
        {
			$this->paramsForWidgets["id"] = $p->gallery;
        }
        else
        {
        	$this->presenceIdentifier = 2; //Create a new gallery message
        	$this->paramsForWidgets["content_id"] = $placeId;
        	$this->paramsForWidgets["content_type"] = "event";
        }	
    }

    
   	public function homeAction()
	{
	}
	
	public function thumbnailAction()
    {
       $eventId = $this->_request->getParam("id");
		$event =  $this->m->findByPrimary($eventId);
		$this->viewParams['id'] = $eventId;
	   if (!$event)
	   {
	   			$this->renderError(null, __("Could not find the place"));
	   			return;
	   }		
		 if ($this->_request->isPost())
		 {
			 $fileName = $_FILES['myFile']['name'];
			 if($_FILES['myFile']['name']){
							$posterId = $event['poster_id'];
							$ustoreDir = APP_PATH."/public/ustore/$posterId/images/original/event/$eventId/thumb/";
							if (!file_exists($ustoreDir))
										mkdir($ustoreDir, 0777  , true);
							$ufilesDir = APP_PATH."/public/ufiles/$posterId/images/original/event/$eventId/thumb/" ;
							if (!file_exists($ufilesDir))
										mkdir($ufilesDir, 0777  , true);
							$fileName = $_FILES['myFile']['name'];
							//make sure the file name is unique
							$targetFile = $ustoreDir . $fileName;
							$i = 1;
							while(file_exists($targetFile))
							{
											$fileName = $i . "_" . $_FILES['myFile']['name'];
											$targetFile = $ustoreDir . $fileName;	
											$i++;
							};
							move_uploaded_file($_FILES['myFile']['tmp_name'],$targetFile);
							//require_once APP_PATH."/library/common.php";
							$watermarkDir = APP_PATH."/public/watermark/";
							// now generate copies
							//TODO: if editors, then do watermark
							$ret = generate_image_copies ("ustore", $ustoreDir,$fileName, $watermarkDir, null, null, $posterId, false); //with wm		
							if ($ret == false)
							{
								//remove the uploaded files
						    unlink ($targetFile);
						        }
						   else
						   {
						        	//$this->viewParams['thumb'] = $targetFile;
						        	$thumb = str_replace(APP_PATH, "", $targetFile);
						        	$event->thumb = str_replace("/public/ustore/", "/public/ufiles/", $thumb);
						        	try 
						        	{
						        		$event->save();
						        	}
						        	catch (Exception $e)
						        	{
						        		die($e->getMessage());
						        	}
						    }
				}
		 }
		 if (!is_null($event->thumb))
			$this->viewParams['thumb'] = $event->thumb;
		 
		
    }  
	
	
	public function manageFeaturedEventAction()
	{
		$data = array('status' => 'featured');
		$results = $this->m->search($data);
		$this->viewParams['displayData'] = $this->db->fetchAll($results);
	}
	
	public function prepareDataSearch($requestData)
	{
		$keys = array('id', 'title', 'article_id','poster_id', 'city_id', 'district_id',
					  'key_words','status','category', 'start_time', 'finish_time',
                      'start_day','finish_day','start_date', 'finish_date', 'frequency',
        	          'calendar_type','place_id', 'gallery', 'calendarType',
        	          );
		
		
		//place list + pagination
		if (isset($requestData['events_per_page']))
			$currentSearchData['events_per_page'] = $requestData['events_per_page'];
		
		else if (!isset($currentSearchData['events_per_page']))
				$currentSearchData['events_per_page'] = $requestData['events_per_page'] = 10;
			else
			 	$requestData['events_per_page'] = $currentSearchData['events_per_page'];
			
		if (isset($requestData['page']))
			$currentSearchData['page'] = $requestData['page'];
		else
			$currentSearchData['page'] = $requestData['page'] = 1;
		
		if(isset($requestData['cluSearch']))
			$currentSearchData['cluSearch'] = $requestData['cluSearch'];
		
		if(isset($requestData['district_id']))
		{
    		if(is_array($requestData['district_id']))
				$requestData['district_id'] = array_unique($requestData['district_id']);
			else
				$requestData['district_id'] = explode(',', $requestData['district_id']);
		}
		
		if(isset($requestData['remove_district_id']) && isset($requestData['district_id']))
		{
			$removeDistrictId = explode(',', $requestData['remove_district_id']);
			foreach($removeDistrictId as $k => $removeDis)
			{
				if(empty($removeDis))
					unset($removeDistrictId[$k]);
				foreach($requestData['district_id'] as $k => $dis)
				{
					if($removeDis == $dis)
						unset($requestData['district_id'][$k]);
				}
			}
		}
		if(isset($requestData['startDate']))
			$currentSearchData['start_date'] = $requestData['startDate'];
		if(isset($requestData['finishDate']))
			$currentSearchData['finish_date'] = $requestData['finishDate'];
		$currentSearchData = $this->mergeSearchValues($requestData, $currentSearchData, $keys, false);
//		die_a($currentSearchData);
		return $currentSearchData;
	}
    
    public function mergeSearchValues($requestData, $currentSearchData, $arrayKeys, $unset)
	{
		foreach($arrayKeys as $k)
		{
			if (isset($requestData[$k]) && !empty($requestData[$k]))
				$currentSearchData[$k] = $requestData[$k];
			else if ($unset)	
				unset($currentSearchData[$k]);
			//else, keep the $currentSearchData[$k]
		}
		return $currentSearchData;
	}
}

?>
